<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Users extends AdminController {
	
	var $_layoutPath = "templates/admin/layout/layout";
	
	function Users() {
		parent::AdminController ();

		$this->load->library('redux_auth');
		$this->load->model("redux_auth/users_model", "Users");
		$this->load->model("redux_auth/groups_model", "Groups");
		$this->load->config("redux_auth");
		
		$this->lang->load('admin/users');
		
	}
	
	function index($pag = null) {
		$config = array();
		
		$users = $this->Users->getAll($config);
		
		$this->_addData("users", $users);
		
		$this->_render();
	}
	
	function add() {
		$additional_columns = $this->config->item('columns');
	
		$this->load->library('Form_validation');		
		
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
	    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|xss_clean|valid_email|callback_email_check');
	    $this->form_validation->set_rules('group', 'Grupo', 'trim|required|xss_clean');
	    
	    $this->form_validation->set_rules('password', 'Password', 'trim|xss_clean');
	    
	    if($this->input->post("password") != ""){
	    	$this->form_validation->set_rules('passconf', 'Password Confirmacion', 'trim|required|matches[password]');
	    }
	    
		if (!empty($additional_columns))
	    {
	        foreach ($additional_columns as $column)
	        {
	            $this->form_validation->set_rules($column, '');
	        }
	    }

		if ($this->form_validation->run() == TRUE){
			
			$username = $this->input->post('username');
	        $email    = $this->input->post('email');
	        $password = $this->input->post('password');
	        //Si no hemos introducito password, lo autogeneramos
	        if($password == ""){
	        	$pool = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

				$str = '';
				for ($i = 0; $i < 6; $i++)
				{
					$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
				}
				$password = $str;
	        }
	        
	        
	        /** Campos adicionales **/
			$additional_info = array();
			if (!empty($additional_columns))
		    {
		        foreach ($additional_columns as $column)
		        {
		            $additional_info[$column] = $this->input->post($column);
		        }
		    }
		    
		    if($this->Users->register($username, $password, $email, $additional_info)){
		    	
		    	$identity_value = $this->Users->get_by_username($username)->{$identity};
		    	
			    //Cambiamos al grupo seleccionado
			    $this->Users->change_user_group($identity_value, $this->input->post("group"));
			    
			    if($this->input->post("notify") == "true"){
			    
				    //Enviamos un mail con la informacion de usuario
				    $data = array('username' => $username,
		        				'password'   => $password,
		        				'email'      => $email);
		            
					$message = $this->load->view($this->config->item('email_templates').'registration', $data, true);
		            
					$this->load->library('email');
					
					$this->email->clear();
					$this->email->set_newline("\r\n");
					$this->email->from('smorete@gmail.com', 'Auth System');
					$this->email->to($email);
					$this->email->subject('Email Registration');
					$this->email->message($message);
					$this->email->send();
			    }
				
				$this->_addFlashSuccess("Usuario creado correctamente");
				
				redirect("admin/users");
		    }
		
		} else{
			$this->_addData("additional_columns", $additional_columns);
			
			$groups = $groups = $this->Groups->get_all();
			$this->_addData("groups", $groups);
			
			$this->_addData("default_group", $this->Groups->get_by_name($this->config->item("default_group")));
			
			$this->_render();
		}
		
	}
	
	/**
	 * Username check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function username_check($username)
	{
	    $check = $this->Users->username_check($username);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('username_check', 'The username "'.$username.'" already exists.');
	        return false;
	    }
	    
	    return true;
	}
	
	/**
	 * Email check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function email_check($email)
	{
	    $check = $this->Users->email_check($email);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('email_check', 'The email "'.$email.'" already exists.');
	        return false;
	    }
	    
	    return true;
	}

	function edit($id = NULL) {
		if($id != NULL){
			$user = $this->Users->getUserById($id);
			
			$additional_columns = $this->config->item('columns');
			$identity = $this->config->item('identity');
		
			$this->load->library('Form_validation');
			
			if($this->input->post("username") != ""){
				$this->form_validation->set_rules('username', 'Username', "trim|required|xss_clean|callback_edit_username_check[$id]");
			}
			
			if($this->input->post("email") != ""){
		   		$this->form_validation->set_rules('email', 'Email Address', "trim|required|xss_clean|valid_email|callback_edit_email_check[$id]");
			}
			
			$this->form_validation->set_rules('group', 'Grupo', 'trim|required|xss_clean');
			
			if($this->input->post("change_password") == "change" && $this->input->post("password") != ""){
				$this->form_validation->set_rules('password', 'Contraseña', 'trim|required');
				$this->form_validation->set_rules('passconf', 'Confirmación de contraseña', 'trim|required|matches[password]');
			}
		
			if (!empty($additional_columns))
		    {
		        foreach ($additional_columns as $column)
		        {
		            $this->form_validation->set_rules($column, '');
		        }
		    }

			if ($this->form_validation->run() == TRUE){
				//Actualizar Info
				$identity_value = $this->Users->getUserById($id)->{$identity};
				
				$data = array();
				$data['id'] = $id;
				
				if($this->input->post("username") != ""){
					$data['username'] = $this->input->post("username");
				}
				
				if($this->input->post("email") != ""){
			   		$data['email'] = $this->input->post("email");
				}
				
				$data['group_id'] = $this->input->post("group");
				
				if($this->input->post("change_password") == "change" && $this->input->post("password") != ""){
					$data['password'] = $this->input->post("password");
				}
				
				$this->Users->update($data);
				
				$additional_info = array();
				if (!empty($additional_columns))
			    {
			        foreach ($additional_columns as $column)
			        {
			            $additional_info[$column] = $this->input->post($column);
			        }
			    }
			    
			    $this->Users->change_user_info($identity_value, $additional_info);
			    
				$this->_addFlashSuccess("Perfil actualizado correctamente");
				
				redirect("admin/users");
			
			} else{
				$this->_addData("additional_columns", $additional_columns);
				
				if($user != null){
					$this->_addData("user", $user);
				}
				
				$groups = $groups = $this->Groups->get_all();
				$this->_addData("groups", $groups);
			
				$this->_render();
			}
		}
	}
	
	
	public function edit_username_check($username, $id)
	{
		Console::log("Checkeando edit_username_check: (Username: '$username' ID: '$id')");
		
		$user = $this->Users->getUserById($id);
		if($user->username != $username){
		    $check = $this->Users->username_check($username);
		    
		    if ($check)
		    {
		        $this->form_validation->set_message('edit_username_check', 'The username "'.$username.'" already exists.');
		        return false;
		    }
		}
		
		return true;
	}
	
	/**
	 * Email check
	 *
	 * @return void
	 **/
	public function edit_email_check($email, $id)
	{
		Console::log("Checkeando edit_email_check: (Username: '$email' ID: '$id')");
		
		$user = $this->Users->getUserById($id);
		if($user->email != $email){
		    $check = $this->Users->email_check($email);
		    
		    if ($check)
		    {
		        $this->form_validation->set_message('edit_email_check', 'The email "'.$email.'" already exists.');
		        return false;
		    }
		}
	}
	

	function delete($id) {
		if($id != null){
			//$this->Category_model->delete($id);
			$this->_addFlashSuccess("Eliminado correctamente");
		}
		
		redirect ( 'admin/users', 'refresh' );
	}
	
	function group_list(){
		$groups = $this->Groups->get_all();
		$this->_addData("groups", $groups);
		$this->_render();
	}
	
	function group_add(){
		$this->load->library('Form_validation');		
		
		$this->form_validation->set_rules('name', 'Nombre', 'trim|required|xss_clean');
		$this->form_validation->set_rules('description', 'Descripcion');
	    
		if ($this->form_validation->run() == TRUE){
			$name = $this->input->post('name');
			$description = $this->input->post('description');
			
			$this->Groups->create($name, $description);
			$this->_addFlashSuccess("Grupo creado correctamente");
			
			redirect("admin/users/group_list");
		} else{
			$this->_render();
		}
	}
	
	function group_edit($id){
		if($id != NULL){
			$group = $this->Groups->get_by_id($id);
			
			if($group != null){
				$this->load->library('Form_validation');		
		
				$this->form_validation->set_rules('name', 'Nombre', 'trim|required|xss_clean');
				$this->form_validation->set_rules('description', 'Descripcion');
				
				if ($this->form_validation->run() == TRUE){
					$data = array();
					$data["id"] = $id;
					$data["name"] = $this->input->post('name');
					$data["description"] = $this->input->post('description');
					
					if($this->Groups->update($data)){
						$this->_addFlashSuccess("Grupo editado correctamente");
						redirect("admin/users/group_list");
					} else{
						$this->_addFlashError("Errores al editar el grupo");
					}
					
					redirect("admin/users/group_list");
				} else{
					$this->_addData("group", $group);
					$this->_render();
				}
			} else{
				$this->_addError("No existe grupo");
			}
		}
	}
	
	function group_delete($id){
		if($id != null && $id != 1 && $id != 2){
			$this->Groups->delete($id);
			$this->_addFlashSuccess("Eliminado correctamente");
		} else if($id != 1 || $id != 2){
			$this->_addFlashError("No se puede eliminar este grupo");
		}
		
		redirect ( 'admin/users/group_list', 'refresh' );
	}
	
	/*** MI PERFIL ***/
	
	function my_account(){
		/*$additional_columns = $this->config->item('columns');
		$this->_addData("additional_columns", $additional_columns);
		
		$user = $this->redux_auth->profile();
		$this->_addData("user", $user);
		$this->_render();*/
		
		$additional_columns = $this->config->item('columns');
		$identity = $this->config->item('identity');
		
		$this->load->library('Form_validation');
		
		$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|valid_email|callback_my_account_email_check');
		
		$this->form_validation->set_rules('change_password', 'Change Password');
		
		if($this->input->post("change_password") == "change"){
			$this->form_validation->set_rules('password', 'Contraseña', 'trim|required');
			$this->form_validation->set_rules('passconf', 'Confirmación de contraseña', 'trim|required|matches[password]');
		}
		
		if (!empty($additional_columns))
	    {
	        foreach ($additional_columns as $column)
	        {
	            $this->form_validation->set_rules($column, '');
	        }
	    }
		
		if ($this->form_validation->run() == TRUE){
			
			$identity_value = $this->redux_auth->profile()->{$identity};
			
			if($this->input->post("change_password") == "change"){
				$this->redux_auth->change_password($identity_value, $this->input->post("password"));
			}
			
			//Actualizar Info
			$additional_info = array();
			if (!empty($additional_columns))
		    {
		        foreach ($additional_columns as $column)
		        {
		            $additional_info[$column] = $this->input->post($column);
		        }
		    }
		    
		    $this->redux_auth->change_user_info($identity_value, $additional_info);
			
			$this->_addFlashSuccess("Perfil actualizado correctamente");
			
			redirect("admin/users/my_account");
		} else{
			$this->_addData("additional_columns", $additional_columns);
			
			$user = $this->redux_auth->profile();
			$this->_addData("user", $user);
			$this->_render();
		}
	}
	
	/**
	 * Email check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function my_account_email_check($email)
	{
		//Comprobamos si el usuario no ha cambiado su email
		$profile = $this->redux_auth->profile();
		if($profile->email == $email){
			return true;
		}
		
	    $check = $this->Users->email_check($email);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('email_check', 'The email "'.$email.'" already exists.');
	        return false;
	    }
	    
	    return true;
	}
	
	

}
?>
